/**
 * @author lulongwen
 * Date: 2023-03-08 21:57
 * Description: Reactflow 特性案例
 * https://reactflow.dev/docs/examples/overview/
 */

import React, { useCallback } from 'react';
import ReactFlow, {
  addEdge,
  MiniMap,
  Controls,
  Background,
  useNodesState,
  useEdgesState,
  ReactFlowInstance
} from 'reactflow';

import { nodes as initialNodes, edges as initialEdges } from './utils';
import CustomNode from './CustomNode';
import './overview.css';

const nodeTypes = {
  custom: CustomNode,
};

type IProps = {
  thumbnail?: boolean;
}

const OverviewFlow: React.FC<IProps> = (props) => {
  const { thumbnail = false } = props;

  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
  const onConnect = useCallback((params) => setEdges((eds) => addEdge(params, eds)), []);

  const onInit = (reactFlowInstance: ReactFlowInstance) => {
    console.log('flow loaded:', reactFlowInstance)
  }

  /**
   * we are using a bit of a shortcut here to adjust the edge type
   * this could also be done with a custom edge for example
   */
  const edgesWithUpdatedTypes = edges.map((edge) => {
    if (edge.sourceHandle) {
      const edgeType = nodes.find((node) => node.type === 'custom').data.selects[edge.sourceHandle];
      edge.type = edgeType;
    }
    return edge;
  });

  return (
    <ReactFlow
      nodes={nodes}
      edges={edgesWithUpdatedTypes}
      onNodesChange={onNodesChange}
      onEdgesChange={onEdgesChange}
      onConnect={onConnect}
      onInit={onInit}
      fitView={thumbnail}
      attributionPosition='top-right'
      nodeTypes={nodeTypes}
    >
      {
        !thumbnail && (
          <MiniMap
            className='h-24' // 96px
            zoomable
            pannable
          />
        )
      }
      { !thumbnail && <Controls /> }
      <Background color='#aaa' gap={16} />
    </ReactFlow>
  );
};

export default OverviewFlow;
